package com.bysc.userservice.service.impl;

import com.bysc.userservice.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    /*
     * springboot 提供的一个发送邮件的简单抽象， 直接注入即可
     */
    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.from}")
    private String from;

    /**
     * 发送邮件
     * @param to        收件人
     * @param subject   主题
     * @param content   内容
     */
    @Override
    public void sendMail(String to, String subject, String content) {

        // 创建一个邮箱消息对象
        SimpleMailMessage message = new SimpleMailMessage();

        // 配置邮件发送人
        message.setFrom(from);

        // 邮件的收件人
        message.setTo(to);

        // 邮件的主题
        message.setSubject(subject);

        // 邮件的内容
        message.setText(content);

        // 发送邮件
        mailSender.send(message);

        log.info("邮件发送成功：{}", message);

    }

    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message,true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //携带附件
            FileSystemResource file = new FileSystemResource(filePath);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
            messageHelper.addAttachment(fileName,file);

            mailSender.send(message);
            log.info("邮件加附件发送成功！");
        } catch (MessagingException e) {
            log.error("发送失败："+e);
        }
    }

}